import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Badge, Drawer, Icon as AIcon, Modal, Tooltip, Checkbox, Tree, DatePicker, Form } from 'antd';
import { afterCloseModal } from '@/utils/utils';
import ValveData from './../ValveFlowMeterSite/ValveData';
import Map from 'ol/Map';
import Overlay from 'ol/Overlay';
import View from 'ol/View';
import Control from 'ol/control';
import TileLayer from 'ol/layer/Tile';
import GeoJSON from 'ol/format/GeoJSON';
import OlStyleStyle from 'ol/style/Style';
import {unByKey} from 'ol/Observable';
import {getArea, getLength} from 'ol/sphere';
import Draw from 'ol/interaction/Draw';
import { DragBox, Select } from 'ol/interaction';
import BuildModalTitle from '@/components/BuildModalTitle';
import { boundingExtent, getCenter } from 'ol/extent';
import CircleStyle from 'ol/style/Circle';
// 图层
import { Vector } from 'ol/layer';
// 数据源
import { Vector as VectorSource } from 'ol/source';
// 要素
import Feature from 'ol/Feature';
// 样式
import { Icon, Style, Text, Fill, Stroke } from 'ol/style';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import Vectors from 'ol/layer/Vector.js';
// 坐标系转化
import { fromLonLat, toLonLat } from 'ol/proj';
import './../Home/openlayers.less';
import './../LeafletImg/index.less';
import PipChart from './../Home/dashboard';
import shuang from './../../images/shuang.png';
import liuliang from './../../images/shuang.png';
import liuliang_red from './../../images/shuang_red.png';
import yaogan from './../../images/yaogan.jpg';
import jiedao from './../../images/jiedao.jpg';
import yali_blue from './../../images/yali_blue.png';
import yali_warm from './../../images/yali_red.png';
import yali_grey from './../../images/yali_red.png';
import issure_arrow from './../../images/arrow-right.png';
// import yali_warm from './../../images/yali_red.gif';
import Detail from '../Pressure_sensors/Detail';
import SelectModalContent from './SelectModal';
import Chart from '../LeafletImg/Chart';
import OverwriteChart from './OverwriteChart';
import find from 'lodash/find';
const FormItem = Form.Item;
const { TreeNode } = Tree;
const noSHowIcon = 11.5;
const noSHowText = 13;
const colors = ['#6a8eff', '#91cc75', '#fac858', '#ee6666'];

@connect(({ issue_map, loading }) => ({
  issue_map,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollInterval = '';
    this.map = null;
    this.state = {
      points: [],
      markerArr: [],
      editRecord: {},
      selectFeature: [],
      canDrag: false,
      pipePointData: {},
      calculateType:'',
      data: [{
        name:'帅学华',
        data: [[89.19352933182229, 42.9726511229365],
          [89.22813421343413, 42.963751899309216],
          [89.2377884738838, 42.96806405504876],
          [89.2449351342167, 42.96925672560954],
          [89.22508579642822, 42.95934402374567],
          [89.23041147442375, 42.95583399275816],
          [89.25897769487078, 42.9514560086312]],
      },
        {
          name:'吾斯曼江·吾买尔',
          data: [[89.17682915350996, 42.95801046791968],
            [89.17717247626388, 42.954869614084004],
            [89.18541222235761, 42.950346502925555],
            [89.18627052924239, 42.94544609071241],
            [89.1931369843205, 42.94557174718099],
            [89.19159203192794, 42.9404196216459]],
        },
        {
          name:'帕提古丽·阿帕尔',
          data: [[89.19303753803464, 42.962072362397606],
            [89.19252255390377, 42.95553963761503],
            [89.19355252216549, 42.949885758282164],
            [89.20471051166744, 42.95076528473686],
            [89.19921734760494, 42.94624187193648],
            [89.2023399014107, 42.95274254812398],
            [89.20495689561507, 42.95709562106191],
            [89.20771663495789, 42.96134392332266],
            [89.20738356296826, 42.953978852145326],

            [89.21138042684407, 42.96472146252063],
          ],
        }],
    };
  }

  changeMapType = (maptype) => {
    const { dispatch, issue_map: { mapType } } = this.props;
    if (maptype === mapType) {
      return false;
    }
    dispatch({
      type: 'issue_map/changeMapType',
      payload: maptype,
    });

  };

  componentDidMount() {
    const { dispatch, issue_map: { pageLoaded } } = this.props;
    this.hadPressPopup = false;
    this.hadFlowMeterPopup = false;
    this.hadPipPopup = false;
    console.log('pageLoaded', pageLoaded);
    if (pageLoaded) {
      this.renderMap();
    } else {
      this.renderMap();



    }
    document.addEventListener( 'onmousedown',function(e) {
      console.log(e.button)
    })
  }

  componentWillUnmount() {
    if (this.timer) {
      console.log('clearInterval(this.timer)');
      clearInterval(this.timer);
    }
    if (this.onePointDataTimer) {
      console.log(' clearTimeout(that.onePointDataTimer)');
      clearTimeout(this.onePointDataTimer);
    }
  }

  renderLine = (data, color) => {
    const coordinates = data.map((item, index) => {
      return fromLonLat(item);
    });
    let lineFeature = new Feature(
      new LineString(coordinates),
    );
    let lineFeatureSource = new VectorSource({
      features: [lineFeature],
    });

    let styleFunction = function(feature) {
      let geometry = feature.getGeometry();
      let length = geometry.getLength();//获取线段长度
      let dradio = 0.05;//投影坐标系，如3857等，在EPSG:4326下可以设置dradio=10000
      let styles = [
        // linestring
        new Style({
          stroke: new Stroke({
            width: 6,
            color: color,
          }),
          fill: new Fill({
            color: color,
          }),
        })];
      for (let i = 0; i <= 1; i += dradio) {
        let arrowLocation = geometry.getCoordinateAt(i);
        geometry.forEachSegment(function(start, end) {
          if (start[0] == end[0] || start[1] == end[1]) return;
          var dx1 = end[0] - arrowLocation[0];
          var dy1 = end[1] - arrowLocation[1];
          var dx2 = arrowLocation[0] - start[0];
          var dy2 = arrowLocation[1] - start[1];
          if (dx1 != dx2 && dy1 != dy2) {
            if (Math.abs(dradio * dx1 * dy2 - dradio * dx2 * dy1) < 0.001) {
              var dx = end[0] - start[0];
              var dy = end[1] - start[1];
              var rotation = Math.atan2(dy, dx);
              styles.push(new Style({

                geometry: new Point(arrowLocation),

                image: new Icon({
                  src: issure_arrow,
                  anchor: [0.75, 0.5],
                  rotateWithView: false,

                  rotation: -rotation + Math.PI,

                }),
              }));
            }
          }
        });
      }

      return styles;
    };

    let lineLayer = new Vector({
      source: lineFeatureSource,
      zIndex: 12,
      style: styleFunction,
    });
    this.map.addLayer(lineLayer);


    let pointFeature = [];
    for (let i = 0; i < coordinates.length; i++) {
      let point = this.setPoint(coordinates[i], {name:'工单内容'}, color, i);
      pointFeature.push(point);
    }
    let pressSource = new VectorSource({
      features: pointFeature,
    });
    let pressLayer = new Vector({
      source: pressSource,
      zIndex: 13,
    });
    // 将标注图层添加到地图上
    this.map.addLayer(pressLayer);
  };
  renderMap = () => {
    const that = this;
    const { dispatch, issue_map: { layers, zoom, center } } = this.props;
    let map = this.map = new Map({
      target: 'mapDiv',
      layers: layers,
      view: new View({
        center: fromLonLat(center),//经纬度
        zoom: zoom,
        // maxZoom: 17.6,
        // minZoom: 13.5,
      }),
    });
    console.log('renderMap');

    for (let i = 0; i < this.state.data.length; i++) {
      this.renderLine(this.state.data[i].data, colors[i]);
    }
    // let select = new Select({
    //   layers: [],
    // });
    let select = new Select({
      filter: function(feature, layer) {
        let isTrue = feature.get('长度');
        return Boolean(isTrue);
      },
      style: new Style({
        stroke: new Stroke({
          color: 'rgb(255,0,246)',
          width: 6,
        }),
      }),
    });
    map.addInteraction(select);

    let selectedFeatures = this.selectedFeatures = select.getFeatures();

    let dragBox = new DragBox({
      condition: function() {
        return that.state.canDrag;
      },
    });

    map.addInteraction(dragBox);

    dragBox.on('boxend', function() {
      var rotation = map.getView().getRotation();
      console.log('rotation', rotation);
      var oblique = rotation % (Math.PI / 2) !== 0;
      var candidateFeatures = oblique ? [] : selectedFeatures;
      var extent = dragBox.getGeometry().getExtent();
      // console.log('oblique', oblique);
      // console.log('extent', extent);
    });

    dragBox.on('boxstart', function() {
      console.log('boxstart');
      selectedFeatures.clear();
    });

    //绘制弹出框
    let press_container = document.getElementById('press-popup');
    let header = document.getElementById('popup-header');
    let popupCloser = document.getElementById('popup-closer');
    let press_popup = new Overlay({
      //设置弹出框的容器
      element: press_container,
      //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
      autoPan: true,
    });
    popupCloser.addEventListener('click', function() {
      press_popup.setPosition(undefined);
    });

    map.on(['click'], function(e) {
      console.log(toLonLat(e.coordinate));
      var feature = map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        return feature;
      });
      if (feature) {
        let data_set = feature.get('data_set');
        console.log('data_set',data_set)
        if(data_set){
          let coordinates = feature.getGeometry().getCoordinates();
          header.innerHTML = '<span>工单详情</span>';
          press_popup.setPosition(coordinates);
          that.map.addOverlay(press_popup);
        }
      }else{
        press_popup.setPosition(undefined);
      }
    });

    map.on('moveend', function(e) {
      let zoom = map.getView().getZoom();  //获取当前地图的缩放级别
      let center = map.getView().getCenter();
      console.log(toLonLat(center));
      console.log(zoom);
      dispatch({
        type: 'issue_map/changeCenterAndZoom',
        payload: {
          zoom, center: toLonLat(center),
        },
      });
    });

  };
  setCenter = () => {
    let view = this.map.getView();
    // view.setZoom(14);
    view.setZoom(12);
    view.setCenter([89.21655514667722, 42.96389386391127]);  //设置当前地图的显示中心位置

  };
  ZoonIn = () => {
    let view = this.map.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom + 1);
  };
  ZoonOut = () => {
    let view = this.map.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom - 1);
  };
  setPoint = (coord, data_set, color, i) => {
    let point = new Feature({
      geometry: new Point(coord),
      data_set: data_set,
    });
    //设置图标的样式
    point.setStyle(this.setMakerStyle(point, color, i));
    return point;
  };
  setMakerStyle = (feature, color, i) => {
    return new Style({
      image: new CircleStyle({
        fill: new Fill({
          color: '#fff',
        }),
        stroke: new Stroke({
          color: color,
          width: 4,
        }),
        radius: 8,
      }),
      /**{olx.style.IconOptions}类型*/
      text: new Text({
        //位置
        textAlign: 'center',
        //基准线
        textBaseline: 'middle',
        //文字样式
        font: 'normal 12px 微软雅黑',
        offsetY: 22,
        //文本内容
        // text: zoom < noSHowText ? '' : feature.get('data_set').name,
        text: '',
        //文本填充样式（即文字颜色）
        fill: new Fill({ color: '#ffffff' }),
        backgroundFill: status ? new Fill({ color: '#3b79fe' }) : new Fill({ color: '#fe2a04' }),
        padding: [3, 0, 0, 3],
      }),
    });
  };
  createMeasureTooltip=()=> {
    let measureTooltipElement;
    let measureTooltip;
    if (measureTooltipElement) {
      measureTooltipElement.parentNode.removeChild(measureTooltipElement);
    }
    measureTooltipElement = document.createElement('div');
    measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
    measureTooltip = new Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      positioning: 'bottom-center',
    });
    this.map.addOverlay(measureTooltip);
  }
  addInteraction=()=>{
    let tip=document.querySelectorAll('.ol-tooltip-static')
    for(let i=0;i<tip.length;i++){
      tip[i].parentNode.removeChild(tip[i])
    }
    const that=this;
    let formatArea = function (polygon) {
      console.log('计算面积')
      let area = getArea(polygon);
      let output;
      if (area > 10000) {
        output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
      } else {
        output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
      }
      return output;
    };

    let formatLength = function (line) {
      console.log('计算长度')
      let length = getLength(line);
      let output;
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
      } else {
        output = Math.round(length * 100) / 100 + ' ' + 'm';
      }
      return output;
    };
    let measureTooltipElement;
    let measureTooltip;
    let createMeasureTooltip = function() {
      if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
      }
      measureTooltipElement = document.createElement('div');
      measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
      measureTooltip = new Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
      });
      that.map.addOverlay(measureTooltip);
    }


    let type=this.state.calculateType;
    if(this.drawVector){
      this.map.removeLayer(this.drawVector);
      this.drawSource=null;
      this.drawVector=null;
      this.map.removeInteraction(this.draw);

    }
    let source = this.drawSource=new VectorSource({wrapX: false});

    let vector = this.drawVector= new Vector({
      source: source,
      style: new Style({
        fill: new Fill({
          color: 'rgba(255, 255, 255, 0.2)',
        }),
        stroke: new Stroke({
          color: '#ffcc33',
          width: 2,
        }),
        image: new CircleStyle({
          radius: 7,
          fill: new Fill({
            color: '#ffcc33',
          }),
        }),
      }),
    });
    this.map.addLayer(vector);
    let draw = this.draw=new Draw({
      source: source,
      type: type
    });
    this.map.addInteraction(draw);
    createMeasureTooltip();
    let listener;
    let sketch;
    draw.on('drawstart', function (evt) {
      // set sketch
      sketch = evt.feature;
      listener = sketch.getGeometry().on('change', function (evt) {
        let geom = evt.target;
        let tooltipCoord = evt.coordinate;
        let output;
        if (geom instanceof Polygon) {
          let p=geom.clone();
          let circleIn4326 = p.transform(that.map.getView().getProjection(),'EPSG:3857');
          output = formatArea(circleIn4326);
          tooltipCoord = geom.getInteriorPoint().getCoordinates();
        } else if (geom instanceof LineString) {
          let p=geom.clone();
          let circleIn4326 = p.transform(that.map.getView().getProjection(),'EPSG:3857');
          output = formatLength(circleIn4326);
          tooltipCoord = geom.getLastCoordinate();
        }
        measureTooltipElement.innerHTML = output;
        measureTooltip.setPosition(tooltipCoord);
      });
    });
    draw.on('drawend', function () {
      measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
      measureTooltip.setOffset([0, -7]);
      sketch = null;
      measureTooltipElement = null;
      createMeasureTooltip();
      unByKey(listener);
    });

  }
  render() {
    const { pipePointData } = this.state;
    const {
      dispatch, issue_map: {
        data, mapType, pointData, flowMeterData, flowMeterVisiable, pressVisiable,
        showMapType, pipeVisiable, designCheckedKeys, pipeCount, pipeLength, flowMeterPointData, showDepth,
        workstations1Visiable,
      },
    } = this.props;
    const that = this;
    return <div style={{
      height: '100%',
      width: '100%',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <div id={'mapDiv'} style={{
        display: 'flex',
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      </div>
      <div id="press-popup" className="ol-popup">
        <a href="#" id="popup-closer" className="ol-popup-closer"></a>
        <div id="popup-header" className={'ol-popup-header'}></div>
        <div id="popup-content" className={'ol-popup-content'}>
          <table className={'custom-table'}>
            <tbody>
            {/*  <tr>
              <td className={'custom-table-title'}>上传时间</td>
              <td className={'custom-table-value'}>{pointData.my_time}</td>
            </tr>*/}
            <tr>
              <td className={'custom-table-title'}>工单主题</td>
              <td
                className={'custom-table-value'}>
                水表1292837302发生倒流
              </td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>处理结果</td>
              <td
                className={'custom-table-value'}>
                已完成处理
              </td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>处理时间</td>
              <td
                className={'custom-table-value'}>
                2021-02-25 12:09:87
              </td>
            </tr>
            </tbody>
          </table>
          <span onClick={() => {
            this.setState({
              infoModal: true,
            });
          }} className={'success'} style={{ cursor: 'pointer' }}>查看详情</span>
        </div>
      </div>
      <div id="info"></div>
      <div className="summary-info2">
        <FormItem label={'开始日期'} style={{color:'#fff',marginBottom:'5px'}}>
          <DatePicker />
        </FormItem>
        <FormItem label={'结束日期'} style={{color:'#fff',marginBottom:'10px'}}>
          <DatePicker />
        </FormItem>
        <Checkbox.Group style={{ width: '100%' }} >
          {
            this.state.data.map((item,index)=>{
              return  <div key={index} style={{marginBottom:'10px',fontWeight:'bold'}}><Checkbox ><span style={{color:colors[index]}}>{item.name}</span></Checkbox></div>
            })
          }

        </Checkbox.Group>

      </div>
      <div className={`maptype ${showMapType ? 'maptype_active' : ''}`}>
        <h3>图层控制</h3>
        <div className="maptype_item">
          <img src={yaogan} alt=""/>
          <span className={mapType === 'sensing' ? 'active' : ''} onClick={() => {
            this.changeMapType('sensing');
          }}>遥感图</span>
        </div>
        <div className="maptype_item">
          <img src={jiedao} alt=""/>
          <span className={mapType === 'road' ? 'active' : ''} onClick={() => {
            this.changeMapType('road');
          }}>街道图</span>
        </div>
      </div>
      <div className="map_control" style={{ bottom: showDepth ? '260px' : '10px' }}>
        <Tooltip title={'全图'}>
          <div className="map_control_item" onClick={this.setCenter}>

            <AIcon type="border-outer"/>
          </div>
        </Tooltip>
        <Tooltip title={'放大'}>
          <div className="map_control_item" onClick={this.ZoonIn}>

            <AIcon type="plus-circle"/>

          </div>
        </Tooltip>
        <Tooltip title={'缩小'}>
          <div className="map_control_item" onClick={this.ZoonOut}>

            <AIcon type="minus-circle"/>

          </div>
        </Tooltip>
        <Tooltip title={'框选'}>
          <div className="map_control_item" onClick={() => {
            this.setState({
              canDrag: true,
            });
          }}>

            <AIcon type="select"/>

          </div>
        </Tooltip>
        <Tooltip title={'显示/隐藏切换图层'}>
          <div className="map_control_item" onClick={() => {
            dispatch({
              type: 'issue_map/changeShowMapType',
              payload: !showMapType,
            });
          }}>

            <AIcon type="snippets"/>
          </div>
        </Tooltip>
        <Tooltip title={'距离测算'}>
          <div className="map_control_item" onClick={() => {
            this.setState({
              calculateType:'LineString'
            },function() {
              this.addInteraction()
            })
          }}>
            <AIcon type="column-height"/>
          </div>
        </Tooltip>
        <Tooltip title={'面积测算'}>
          <div className="map_control_item" onClick={() => {
            this.setState({
              calculateType:'Polygon'
            },function() {
              this.addInteraction()
            })
          }}>
            <AIcon type="radius-setting"/>
          </div>
        </Tooltip>
        {
          (this.state.calculateType==='LineString'||this.state.calculateType==='Polygon')&&
          <div onClick={()=>{
            if(this.drawVector){
              this.map.removeLayer(this.drawVector);
              this.drawSource=null;
              this.drawVector=null;
              this.map.removeInteraction(this.draw);
              let tip=document.querySelectorAll('.ol-tooltip-static')
              for(let i=0;i<tip.length;i++){
                tip[i].parentNode.removeChild(tip[i])
              }
            }
            this.setState({
              calculateType:''
            })

          }} style={{right:this.state.calculateType==='LineString'?'60px':'0px'}} className={'hidden-calculate'}>
            取消测算
          </div>
        }

      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.selectModal} modalClass="selectModal" title="选择信息"/>}
        visible={this.state.selectModal}
        destroyOnClose
        width={1100}
        footer={[]}
        centered
        className="selectModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.selectedFeatures.clear();
          this.setState({ selectModal: false, selectFeature: [] });
        }}

      >
        <SelectModalContent showDetail={(row) => {
          this.setState({
            editRecord: row,
            infoModal: true,
          });
        }}
                            showWorkstationDetail={(item) => {
                              this.setState({
                                workstationModal: true,
                                editRecord: item,
                              });
                            }}

                            showWaterDetail={this.showWaterDetail}
                            selectFeature={this.state.selectFeature}></SelectModalContent>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={this.state.modalTitle + '历史数据'}/>}
        destroyOnClose
        visible={this.state.editModal}
        width={900}
        centered
        onOk={() => {
          this.setState({ editModal: false, waterType: [] });
        }}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, waterType: [] });
        }}

      >
        <Chart editRecord={this.state.waterType}></Chart>

      </Modal>
    </div>;
  }
}

export default BasicList;
